package com.wan.api.controller;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wan.entity.*;
import com.wan.service.*;
import entity.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xzx
 * @date 2021/4/14 15:49
 */
@RestController
@RequestMapping("/bs/game")
public class GameUserController extends BaseController {
    @Autowired
    private GameUserService gameUserService;
    @Autowired
    private GameRoleService roleService;
    @Autowired
    private GameAreaService areaService;
    @Autowired
    private GameFriendService friendService;
    @Autowired
    private GameRecordService recordService;
    @Autowired
    private GameHeroService heroService;


    @RequestMapping("/get/user")
    public ResultBean getUser(){
        Integer userId = getUserId();
        return new ResultBean(200,"成功",userId);
    }


    @RequestMapping("/rolelist")
    public ResultBean roleList(){
        Integer id = getUserId();
        QueryWrapper<GameRole> gameRoleQueryWrapper = new QueryWrapper<>();
        gameRoleQueryWrapper.eq("user_id",id);
        List<GameRole> gameRoles = roleService.list(gameRoleQueryWrapper);
        List<JSONObject> jsonObjects = gameRoles.stream().map(role -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("roleName",role.getRoleName());
            GameArea area = areaService.getById(role.getAreaId());
            jsonObject.put("areaName",area.getAreaName());
            jsonObject.put("id",role.getId());
            return jsonObject;
        }).collect(Collectors.toList());
        return new ResultBean(200,"成功",jsonObjects);
    }


    @RequestMapping("/rolelist/{id}")
    public ResultBean roleListFriend(@PathVariable("id") Integer id){
        QueryWrapper<GameRole> gameRoleQueryWrapper = new QueryWrapper<>();
        gameRoleQueryWrapper.eq("user_id",id);
        List<GameRole> gameRoles = roleService.list(gameRoleQueryWrapper);
        List<JSONObject> jsonObjects = gameRoles.stream().map(role -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("roleName",role.getRoleName());
            GameArea area = areaService.getById(role.getAreaId());
            jsonObject.put("areaName",area.getAreaName());
            jsonObject.put("id",role.getId());
            return jsonObject;
        }).collect(Collectors.toList());
        return new ResultBean(200,"成功",jsonObjects);
    }

    /**
     * 添加好友方法
     * @param str
     * @return
     */
    @RequestMapping("/add/friend")
    public ResultBean addFriend(@RequestBody String str){
        Integer selfId = getUserId();
        JSONObject jsonObject = JSON.parseObject(str);
        Integer friendId = jsonObject.getInteger("friendId");
        QueryWrapper<GameFriend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",selfId);
        queryWrapper.eq("friend_id",friendId);
        GameFriend friend = friendService.getOne(queryWrapper);
        if (Objects.nonNull(friend)){
            return new ResultBean(1005,"已经是您的好友");
        }
        GameUser user = gameUserService.getById(friendId);
        friend = new GameFriend();
        friend.setUserId(selfId);
        friend.setCreateTime(new Date());
        friend.setFriendId(friendId);
        friend.setFriendName(user.getNickName());
        friend.setFriendImg(user.getFaceImg());
        friend.setFriendLevel(user.getLevel());
        friend.setFriendSign(user.getSignGe());
        friendService.save(friend);
        return new ResultBean(200,"添加成功");
    }

    /**
     * 查询好友信息
     * @param number
     * @return
     */
    @RequestMapping("/search")
    public ResultBean search(String number){
        QueryWrapper<GameUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_number",number);
        GameUser user = gameUserService.getOne(queryWrapper);
        if (Objects.isNull(user)){
            return new ResultBean(1004,"没有查到好友");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",user.getId());
        jsonObject.put("face",user.getFaceImg());
        jsonObject.put("nickName",user.getNickName());
        jsonObject.put("signGe",user.getSignGe());
        return new ResultBean(200,"成功",jsonObject);
    }


    /**
     * 小程序好友列表
     * @return
     */
    @RequestMapping("/user/info")
    public ResultBean getUserInfo(){
        Integer id = getUserId();
        GameUser user = gameUserService.getById(id);
        QueryWrapper<GameRole> gameRoleQueryWrapper = new QueryWrapper<>();
        gameRoleQueryWrapper.eq("user_id",id);
        List<GameRole> roleList = roleService.list(gameRoleQueryWrapper);
        JSONObject jsonObject = new JSONObject();
        if (roleList.size() == 0){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("face",user.getFaceImg());
            jsonObject1.put("roleName",user.getNickName());
            jsonObject1.put("rank","无段位");
            jsonObject1.put("areaName","没有选择大区");
            jsonObject.put("user",jsonObject1);
        }else {
            List<JSONObject> jsonObjects = roleList.stream().map(role -> {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("face",user.getFaceImg());
                jsonObject2.put("roleName",role.getRoleName());
                jsonObject2.put("rank",role.getRoleRank());
                GameArea area = areaService.getById(role.getAreaId());
                jsonObject2.put("areaName",area.getAreaName());
                return jsonObject2;
            }).collect(Collectors.toList());
            jsonObject.put("user",jsonObjects.get(0));
        }

        QueryWrapper<GameFriend> friendQueryWrapper = new QueryWrapper<>();
        friendQueryWrapper.eq("user_id",id);
        List<GameFriend> list = friendService.list(friendQueryWrapper);

        List<JSONObject> list1 = list.stream().map(item -> {
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("friendId",item.getFriendId());
            jsonObject3.put("friendImg",item.getFriendImg());
            jsonObject3.put("friendName",item.getFriendName());
            jsonObject3.put("friendLevel",item.getFriendLevel());
            jsonObject3.put("friendSign",item.getFriendSign());
            GameUser user1 = gameUserService.getById(item.getFriendId());
            jsonObject3.put("status",user1.getStatus());
            jsonObject3.put("statusStr","游戏离线");
            if (Objects.equals(1,user1.getStatus())){
                jsonObject3.put("statusStr","游戏在线");
            }
            return jsonObject3;
        }).collect(Collectors.toList());
        jsonObject.put("friendList",list1);
        return new ResultBean(200,"成功",jsonObject);
    }

    @RequestMapping("/user/query/friend/{number}")
    public ResultBean getFriend(@PathVariable("number") String number){
        QueryWrapper<GameUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_number",number);
        GameUser user = gameUserService.getOne(queryWrapper);
        return new ResultBean(200,"成功",user);
    }

    @RequestMapping("/roleid/record/{id}")
    public ResultBean roleIdRecord(@PathVariable("id")Integer id){
        GameRole role = roleService.getById(id);
        QueryWrapper<GameRecord> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id",role.getId());
        List<GameRecord> list = recordService.list(queryWrapper1);
        GameUser user = gameUserService.getById(role.getUserId());
        List<JSONObject> list1 = list.stream().map(record -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",record.getId());
            jsonObject.put("gameModelStr",Objects.equals("0",record.getGameModel()) ? "匹配" : "排位");
            jsonObject.put("gameModel",record.getGameModel());
            jsonObject.put("gaemResultStr",Objects.equals("0",record.getGaemResult()) ? "成功" : "失败");
            jsonObject.put("gaemResult",record.getGaemResult());
            Date date = DateUtil.parse(record.getGameStartTime(),"yyyy-MM-dd HH:mm");
            jsonObject.put("gameStartTime",DateUtil.format(date,"MM-dd HH:mm"));
            jsonObject.put("jisha",record.getKillCount()+"/"+record.getAssistCount()+"/"+record.getDeathCount());
            GameHero gameHero = heroService.getById(record.getHeroId());
            jsonObject.put("heroImg",gameHero.getHeroImg());
            jsonObject.put("heroName",gameHero.getHeroName());
            return jsonObject;
        }).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("faceImg",user.getFaceImg());
        jsonObject.put("roleName",role.getRoleName());
        jsonObject.put("areaName",areaService.getById(role.getAreaId()).getAreaName());
        jsonObject.put("level",role.getRoleLevel());
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("list",list1);
        jsonObject1.put("user",jsonObject);
        return new ResultBean(200,"成功",jsonObject1);
    }

    @RequestMapping("/user/record/{friendId}")
    public ResultBean userRecordFriend(@PathVariable("friendId")Integer id){
        QueryWrapper<GameRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<GameRole> roleList = roleService.list(queryWrapper);
        if(roleList.size() == 0){
            return new ResultBean(1002,"没有角色信息");
        }
        GameRole role = roleList.get(0);
        QueryWrapper<GameRecord> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id",role.getId());
        List<GameRecord> list = recordService.list(queryWrapper1);
        GameUser user = gameUserService.getById(id);
        List<JSONObject> list1 = list.stream().map(record -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",record.getId());
            jsonObject.put("gameModelStr",Objects.equals("0",record.getGameModel()) ? "匹配" : "排位");
            jsonObject.put("gameModel",record.getGameModel());
            jsonObject.put("gaemResultStr",Objects.equals("0",record.getGaemResult()) ? "成功" : "失败");
            jsonObject.put("gaemResult",record.getGaemResult());
            Date date = DateUtil.parse(record.getGameStartTime(),"yyyy-MM-dd HH:mm");
            jsonObject.put("gameStartTime",DateUtil.format(date,"MM-dd HH:mm"));
            jsonObject.put("jisha",record.getKillCount()+"/"+record.getAssistCount()+"/"+record.getDeathCount());
            GameHero gameHero = heroService.getById(record.getHeroId());
            jsonObject.put("heroImg",gameHero.getHeroImg());
            jsonObject.put("heroName",gameHero.getHeroName());
            return jsonObject;
        }).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("faceImg",user.getFaceImg());
        jsonObject.put("nickName",user.getNickName());
        jsonObject.put("signGe",user.getSignGe());
        jsonObject.put("roleName",role.getRoleName());
        jsonObject.put("areaName",areaService.getById(role.getAreaId()).getAreaName());
        jsonObject.put("level",role.getRoleLevel());
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("list",list1);
        jsonObject1.put("user",jsonObject);
        return new ResultBean(200,"成功",jsonObject1);
    }






    @RequestMapping("/user/record")
    public ResultBean userRecord(){
        Integer id = getUserId();
        QueryWrapper<GameRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<GameRole> roleList = roleService.list(queryWrapper);
        if(roleList.size() == 0){
            return new ResultBean(1002,"没有角色信息");
        }
        GameRole role = roleList.get(0);
        QueryWrapper<GameRecord> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id",role.getId());
        List<GameRecord> list = recordService.list(queryWrapper1);
        GameUser user = gameUserService.getById(id);
        List<JSONObject> list1 = list.stream().map(record -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",record.getId());
            jsonObject.put("gameModelStr",Objects.equals("0",record.getGameModel()) ? "匹配" : "排位");
            jsonObject.put("gameModel",record.getGameModel());
            jsonObject.put("gaemResultStr",Objects.equals("0",record.getGaemResult()) ? "成功" : "失败");
            jsonObject.put("gaemResult",record.getGaemResult());
            Date date = DateUtil.parse(record.getGameStartTime(),"yyyy-MM-dd HH:mm");
            jsonObject.put("gameStartTime",DateUtil.format(date,"MM-dd HH:mm"));
            jsonObject.put("jisha",record.getKillCount()+"/"+record.getAssistCount()+"/"+record.getDeathCount());
            GameHero gameHero = heroService.getById(record.getHeroId());
            jsonObject.put("heroImg",gameHero.getHeroImg());
            jsonObject.put("heroName",gameHero.getHeroName());
            return jsonObject;
        }).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("faceImg",user.getFaceImg());
        jsonObject.put("nickName",user.getNickName());
        jsonObject.put("signGe",user.getSignGe());
        jsonObject.put("roleName",role.getRoleName());
        jsonObject.put("areaName",areaService.getById(role.getAreaId()).getAreaName());
        jsonObject.put("level",role.getRoleLevel());
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("list",list1);
        jsonObject1.put("user",jsonObject);
        return new ResultBean(200,"成功",jsonObject1);
    }

    @RequestMapping("/record/det/{id}")
    public ResultBean recordDet(@PathVariable("id") Integer id){
        GameRecord record = recordService.getById(id);
        GameHero hero = heroService.getById(record.getHeroId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gameModelStr",Objects.equals(0,record.getGameModel()) ? "匹配模式" : "排位模式");
        jsonObject.put("heroName",hero.getHeroName());
        jsonObject.put("jisha",record.getKillCount()+"/"+record.getAssistCount()+"/"+record.getDeathCount());
        QueryWrapper<GameRecord> gameRecordQueryWrapper = new QueryWrapper<>();
        gameRecordQueryWrapper.eq("gaem_result",0);
        Integer total = recordService.count();
        Integer winCount = recordService.count(gameRecordQueryWrapper);
        BigDecimal bigDecimal = NumberUtil.div(winCount,total,1);
        BigDecimal bigDecimal1 = NumberUtil.mul(bigDecimal,100);
        String shenglv = bigDecimal1.toPlainString()+"%";
        jsonObject.put("shengLv",shenglv);
        jsonObject.put("gameLevel",record.getGameLevel());
        jsonObject.put("team",record.getTotalKillCount()+"/"+record.getTotalAssistCount()+"/"+record.getTotalDeathCount());
        jsonObject.put("money",record.getMoney()+"K");
        jsonObject.put("ta",record.getPushTower());
        jsonObject.put("xiaolongCount",record.getXiaoLongCount());
        jsonObject.put("dalongCount",record.getDaLongCount());
        jsonObject.put("gameStartTime",record.getGameStartTime());
        jsonObject.put("gameEndTime",record.getGameEndTime());
        String gameTime = DateUtil.formatBetween(DateUtil.parse(record.getGameStartTime()),DateUtil.parse(record.getGameEndTime()), BetweenFormater.Level.SECOND);
        jsonObject.put("gameTime",gameTime);
        return new ResultBean(200,"成功",jsonObject);
    }


    @RequestMapping("/get/userinfo")
    public ResultBean getUserInfoSimlp(){
        Integer userId = getUserId();
        GameUser user = gameUserService.getById(userId);
        return new ResultBean(200,"成功",user);
    }

    /**
     * 更新昵称
     * @param userId
     * @param nickName
     * @return
     */
    @RequestMapping("/update/nickname/{userId}")
    public ResultBean updateNickeName(@PathVariable("userId")Integer userId,@RequestBody String nickName){
        JSONObject jsonObject = JSON.parseObject(nickName);
        GameUser user = gameUserService.getById(userId);
        user.setNickName(jsonObject.getString("nickName"));
        gameUserService.updateById(user);
        return new ResultBean(200,"成功");
    }

    /**
     * 更新个性签名
     * @param userId
     * @param sign
     * @return
     */
    @RequestMapping("/update/sign/{userId}")
    public ResultBean updateSign(@PathVariable("userId")Integer userId,@RequestBody String sign){
        JSONObject jsonObject = JSON.parseObject(sign);
        GameUser user = gameUserService.getById(userId);
        user.setSignGe(jsonObject.getString("sign"));
        gameUserService.updateById(user);
        return new ResultBean(200,"成功");
    }

    @RequestMapping("/deletefriend/{friendId}")
    public ResultBean deleteFriend(@PathVariable("friendId")Integer friendId){
        Integer userId = getUserId();
        QueryWrapper<GameFriend> gameFriendQueryWrapper = new QueryWrapper<>();
        gameFriendQueryWrapper.eq("user_id",userId);
        gameFriendQueryWrapper.eq("friend_id",friendId);
        friendService.remove(gameFriendQueryWrapper);
        QueryWrapper<GameFriend> friendQueryWrapper = new QueryWrapper<>();
        friendQueryWrapper.eq("user_id",userId);
        List<GameFriend> list = friendService.list(friendQueryWrapper);

        List<JSONObject> list1 = list.stream().map(item -> {
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("friendId",item.getFriendId());
            jsonObject3.put("friendImg",item.getFriendImg());
            jsonObject3.put("friendName",item.getFriendName());
            jsonObject3.put("friendLevel",item.getFriendLevel());
            jsonObject3.put("friendSign",item.getFriendSign());
            GameUser user1 = gameUserService.getById(item.getFriendId());
            jsonObject3.put("status",user1.getStatus());
            jsonObject3.put("statusStr","游戏离线");
            if (Objects.equals(1,user1.getStatus())){
                jsonObject3.put("statusStr","游戏在线");
            }
            return jsonObject3;
        }).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("friendList",list1);
        return new ResultBean(200,"好友删除成功",jsonObject);
    }


}
